import util.TreeNode;

/**
 * Created by losor on 2017/3/15.
 */
public class _110_BalancedBinaryTree {

    public static void main(String[] args) {
        TreeNode a = new TreeNode(2);
        a.right = new TreeNode(1);
        a.left = new TreeNode(3);
        System.out.println(isBalanced(a));
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        return checkNode(root)!=-1;
    }
    public static int checkNode(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int lh = checkNode(root.left);
        if (lh == -1) {
            return -1;
        }
        int rh = checkNode(root.right);
        if (rh == -1) {
            return -1;
        }
        if (Math.abs(lh - rh) < 2) {
            return Math.max(lh, rh) + 1;
        } else {
            return -1;
        }
    }
}
